package com.skyworth.web.wechat.protocol;

import com.skyworth.utils.StrUtil;
import com.skyworth.utils.TimeUtil;
import com.skyworth.web.admin.table.model.TableModel;
import com.skyworth.web.admin.table.service.ITableService;
import com.skyworth.web.order.domain.OrderModel;
import com.skyworth.web.order.service.NewOrderService;
import com.skyworth.web.order.service.OrderService;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.common.MessageParse;
import com.skyworth.web.wechat.common.WxConstant;
import com.skyworth.web.wechat.common.WxTokenSign;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.entity.TableBindModel;
import com.skyworth.web.wechat.service.AccessTokenService;
import com.skyworth.web.wechat.service.TableBindService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by yuhaichao on 2016/9/6.
 */
@Component
public class ProcessMsg {

    private static final Logger log = LoggerFactory.getLogger(ProcessMsg.class);

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private TableBindService tableBindService;

    @Autowired
    private NewOrderService newOrderService;

    @Autowired
    private ITableService iTableService;

    public String checkToken(HttpServletRequest request){

        try {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");

            if (WxTokenSign.checkSignature(signature, timestamp, nonce)) {
                return echostr;
            }
        } catch (Exception e) {
            log.error("token:"+e);
        }
        return null;

    }

    public String process(HttpServletRequest request){
        String respContent = "";
        try{
            Map<String, String> requestMap = MessageParse.parseXml(request);
            String fromUserName = requestMap.get("FromUserName");
            String toUserName = requestMap.get("ToUserName");
            String msgType = requestMap.get("MsgType");

            if(WxConstant.REQ_MESSAGE_TYPE_EVENT.equals(msgType)){
                String eventType = requestMap.get("Event");
                if(WxConstant.EVENT_TYPE_SUBSCRIBE.equals(eventType)){
                    respContent=WxConstant.GZ_MSG;
                    String eventKey = requestMap.get("EventKey");
                    if(eventKey!=null && eventKey.startsWith(WxConstant.EVENT_KEY_QRC_PRE)) {
                        String scene_str=eventKey.substring(eventKey.indexOf(WxConstant.EVENT_KEY_QRC_PRE)+WxConstant.EVENT_KEY_QRC_PRE.length());
                        respContent = bindTable(scene_str, fromUserName, respContent);
                    }
                    final String userId = fromUserName;
                    new Thread(){
                        public void run(){
                            accessTokenService.saveWxUserInfo(userId);
                        }
                    }.start();
                    if(respContent!=null && !"".equals(respContent)) {
                        respContent = sendTextMessage(fromUserName, toUserName, respContent);
                    }
                }else if(WxConstant.EVENT_TYPE_SCAN.equals(eventType)){
                    String eventKey = requestMap.get("EventKey");
                    respContent = bindTable(eventKey,fromUserName,respContent);
                    if(respContent!=null && !"".equals(respContent)) {
                        respContent = sendTextMessage(fromUserName, toUserName, respContent);
                    }
                }
            }

        }catch(Exception e){
            log.error(e.getMessage());
        }
        return respContent;
    }

    private String bindTable(String scene_str,String userId,String resp){

        long tableId = Long.parseLong(scene_str);
            /*OrderModel om = orderService.getLastParentOrder(tableId);
            if (om == null) {*/
        OrderModel om = newOrderService.getOrderCart(userId);
                TableBindModel tbm = new TableBindModel();
                tbm.setTableId(tableId);
                tbm.setUserId(userId);
                tbm.setState(0);

                //tableBindService.saveTableBind(tbm,om);
                //om = orderService.getLastOrder(userId);
                if(om==null) {
                    tableBindService.save(tbm);
                }else{
                    tableBindService.saveTableBind(tbm,om);
                    final String openid=userId;
                    final String orderId=StrUtil.objectToString(om.id);
                    new Thread(){
                        public void run(){

                    AccessTokenModel atm = accessTokenService.findByAppId(AppSecretInfo.appId);
                    String accessToken = atm.getAccessToken();
                    Map<Object,Object> handleMap = NotifyMsg.orderWaitMsg(openid,orderId, TimeUtil.getNowDateFormat("yyyy年MM月dd日 HH:mm"));
                    ServerEngin.getInstance().sendTemplateMsg(accessToken,handleMap);
                        }
                    }.start();
                    //resp="";
                }

        TableModel tableModel = iTableService.findTable(tableId);
        resp = WxConstant.BIND_MSG;
        resp=resp.replace("{tableName}",tableModel.name);

            /*} else {
                log.info("repeat bind");
            }*/
        return resp;
    }

    private String sendTextMessage(String fromUserName, String toUserName, String message) {
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(fromUserName);
        textMessage.setFromUserName(toUserName);
        textMessage.setCreateTime(new Date().getTime());
        textMessage.setMsgType(MessageParse.RESP_MESSAGE_TYPE_TEXT);
        textMessage.setFuncFlag(0);
        textMessage.setContent(message);
        String respMessage = MessageParse.textMessageToXml(textMessage);
        return respMessage;
    }

    public String menuMsg(){
        AccessTokenModel atm = accessTokenService.findByAppId(AppSecretInfo.appId);
        String accessToken = atm.getAccessToken();
        BaseButton button = new BaseButton();

        String ddUrl=WxConstant.WX_DOMAIN+"wechat/index.html?from=orders#action=orders";

        UrlMenu menu01 = new UrlMenu();
        menu01.setName("我的订单");
        menu01.setType("view");
        menu01.setUrl(ddUrl);

        String dcUrl=WxConstant.WX_DOMAIN+"wechat/index.html";
        UrlMenu menu02 = new UrlMenu();
        menu02.setName("点菜");
        menu02.setType("view");
        menu02.setUrl(dcUrl);

        List<Object> buttonList = new ArrayList<Object>();
        buttonList.add(menu01);
        buttonList.add(menu02);

        button.setButton(buttonList);

        return ServerEngin.getInstance().createMenu(accessToken,button);

    }
}
